import { useRef } from "react";
import eventBus, { useSubscribe } from "../eventBus";

export default function useRuleTrigger(tplData) {
  const cacheRef = useRef({});
  //监听字段blur事件来触发规则
  useSubscribe("field.blur", (field = "",value) => {
    //主表filed不会带.  子表code group以.隔开
    if (cacheRef.current[field] !== false) {
      //主表
      if (field.startsWith("form.form_data.main.")) {
        let originField = field.replace("form.form_data.main.", "");
        if (~tplData.originRulesStr.indexOf(`"${originField}"`) || ~tplData.originRulesStr.indexOf(`[main.${originField}]`)) {
          for (const key in tplData.rules) {
            if (~tplData.rules[key].indexOf(originField)) {
              eventBus.publish(`rule.${key}`);
            }
          }
        } else {
          cacheRef.current[field] = false;
        }
      } else if (field.startsWith("form.form_data.children.")) {
        //子表
        let originField = field.replace("form.form_data.children.", "").replace(/\[.*\]/, "");
        //目前设计器里面子表字段不能用
        if (~tplData.originRulesStr.indexOf(`"${originField}"`) || ~tplData.originRulesStr.indexOf(`[children.${originField}]`) ) {
          for (const key in tplData.rules) {
            if (~tplData.rules[key].indexOf(originField)) {
              eventBus.publish(`rule.${key}`, Number(field.split('[').pop().split(']')[0]));
            }
          }
        } else {
          cacheRef.current[field] = false;
        }
      }
    }
  });
}
